//
//  ThemeNavigationController.swift
//  UIKitExtentions
//
//  Created by Alean on 2022/12/2.
//

import UIKit

public func mainNavigationController() -> UINavigationController? {
    if let window = UIApplication.shared.keyWindow {
        if let controller = window.rootViewController as? UINavigationController {
            return controller
        }
        if let tabController = window.rootViewController as? UITabBarController {
            if let controller = tabController.selectedViewController as? UINavigationController {
                return controller
            }
        }
    }
    return nil
}

// MARK: 获取上层的 Controller
public func topViewController() -> UIViewController? {
    if let window = UIApplication.shared.keyWindow {
        return getTopController(window.rootViewController)
    }
    return nil
}

// MARK: 获取上层的 详情 Controller
public func topVisibleController() -> UIViewController? {
    return topViewController()?.visibleViewController
}

public func getTopController(_ vc: UIViewController?) -> UIViewController? {
    if vc?.presentedViewController != nil {
        return getTopController(vc?.presentedViewController)
    }

    if let currentVC = vc as? UITabBarController {
        return getTopController(currentVC.selectedViewController)
    }

    if let currentVC = vc as? UINavigationController {
        return getTopController(currentVC.topViewController)
    }
    
    if let currentVC = vc as? UIPageViewController,
       currentVC.viewControllers?.count == 1,
       let controller = currentVC.viewControllers?.first {
        return getTopController(controller)
    }

    return vc
}

public func getTopVisibleController(_ vc: UIViewController?) -> UIViewController? {
    if let controller = getTopController(vc)?.visibleViewController {
        return getTopVisibleController(controller)
    } else {
        return vc
    }
}

public func topNavigationController() -> UINavigationController? {
    if let window = UIApplication.shared.keyWindow {
        if let controller = window.rootViewController as? UINavigationController {
            return controller
        }
        if let tabController = window.rootViewController as? UITabBarController {
            if let controller = tabController.visibleViewController {
                if let controller = controller.navigationController {
                    return controller
                }
            }
        }
    }
    return mainNavigationController()
}

@objc public extension UIViewController {
    private static var AssociatedBackItem: UInt8 = 0
    @objc var autoCreateBackItem: Bool {
        get {
            return objc_getAssociatedObject(self, &UIViewController.AssociatedBackItem) as? Bool ?? true
        }
        set {
            objc_setAssociatedObject(self, &UIViewController.AssociatedBackItem, newValue, .OBJC_ASSOCIATION_ASSIGN)
        }
    }

    var visibleViewController: UIViewController? {
        if let navigationController = self as? UINavigationController {
            return navigationController.topViewController?.visibleViewController
        } else if let tabBarController = self as? UITabBarController {
            return tabBarController.selectedViewController?.visibleViewController
        } else if let presentedViewController = presentedViewController {
            return presentedViewController.visibleViewController
        } else {
            return self
        }
    }
}

open class ThemeNavigationController: UINavigationController, UINavigationControllerDelegate, UIGestureRecognizerDelegate {

    open override func viewDidLoad() {
        super.viewDidLoad()

//        let appearance = UIBarButtonItem.appearance()
//        appearance.setBackButtonTitlePositionAdjustment(UIOffset.init(horizontal: 0.0, vertical: -60), for: .default)
//        navigationBar.barTintColor = UIColor.init(red: 250/255.0, green: 250/255.0, blue: 250/255.0, alpha: 0.8)
//        #if swift(>=4.0)
//            navigationBar.titleTextAttributes = [NSAttributedString.Key.foregroundColor : UIColor.init(red: 38/255.0, green: 38/255.0, blue: 38/255.0, alpha: 1.0), NSAttributedString.Key.font: UIFont.systemFont(ofSize: 16.0)]
//        #elseif swift(>=3.0)
//            navigationBar.titleTextAttributes = [NSForegroundColorAttributeName : UIColor.init(red: 38/255.0, green: 38/255.0, blue: 38/255.0, alpha: 1.0), NSFontAttributeName: UIFont.systemFont(ofSize: 16.0)];
//        #endif
//        navigationBar.tintColor = UIColor.init(red: 38/255.0, green: 38/255.0, blue: 38/255.0, alpha: 1.0)
////        navigationItem.title = "Example"
//        
//        navigationBar.isTranslucent = true
        delegate = self
//        interactivePopGestureRecognizer?.delegate = self
//        interactivePopGestureRecognizer?.isEnabled = true
    }
    
    open override var preferredStatusBarStyle: UIStatusBarStyle {
        return .default
    }

    open override var childForStatusBarStyle: UIViewController? {
        return self.topViewController
    }

    @objc public var editButton: UIButton = {
        let editButton = UIButton()
        editButton.frame = CGRect(x: 0, y: 0, width: 44, height: 44)
        editButton.setImage(UIImage(named: "icon_20px_arrow_left")?.withRenderingMode(.alwaysOriginal) ?? UIImage(), for: .normal)
        editButton.imageEdgeInsets = UIEdgeInsets(top: 6, left: -12, bottom: 6, right: 12)
        editButton.addTarget(self, action: #selector(popTopViewController), for: .touchUpInside)
        return editButton
    }()

    @objc public var defaultBackItem: UIBarButtonItem {
        let customView = UIView(frame: CGRect(x: 0, y: 0, width: 44, height: 44))
        customView.addSubview(editButton)
        let editItem = UIBarButtonItem(customView: customView)
        return editItem
    }

    
    public func navigationController(_: UINavigationController, willShow viewController: UIViewController, animated _: Bool) {
        if viewControllers.first != viewController {
            if viewController.autoCreateBackItem {
                viewController.navigationItem.leftBarButtonItem = defaultBackItem
            }
        }
    }

    public func navigationController(_ navigationController: UINavigationController, didShow viewController: UIViewController, animated: Bool) {
        if (navigationController.viewControllers.count == 1) {
            navigationController.interactivePopGestureRecognizer?.isEnabled = false
            navigationController.interactivePopGestureRecognizer?.delegate = nil
        } else {
            navigationController.interactivePopGestureRecognizer?.isEnabled = true
            navigationController.interactivePopGestureRecognizer?.delegate = self
        }

//        if viewControllers.first != viewController {
//            if viewController.autoCreateBackItem {
//                viewController.navigationItem.leftBarButtonItem = defaultBackItem
//            }
//        }
    }
    
    open override func pushViewController(_ viewController: UIViewController, animated: Bool) {
        interactivePopGestureRecognizer?.isEnabled = false
        super.pushViewController(viewController, animated: animated)
    }
    
    @objc public func popTopViewController() {
        popViewController(animated: true)
    }


    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destination.
        // Pass the selected object to the new view controller.
    }
    */

}

public extension UINavigationController {
    @objc func pushViewController(_ viewController: UIViewController, completion: (() -> Void)? = nil) {
        CATransaction.begin()
        CATransaction.setCompletionBlock(completion)
        pushViewController(viewController, animated: true)
        CATransaction.commit()
    }
}
